/**
 * 指令常用方法
 */

import supportEvent from '@/utils/is-support-event';

/**
 * 获取文本框元素
 *
 * @param  {HTMLElement} el 元素
 * @return {HTMLElement}
 */
export const getInputElement = (el) => {
    if (el.tagName.toLowerCase() !== 'input') {
        el = el.querySelector('input');
    }
    return el;
};

/**
 * 使用vm数据获取指令
 *
 * @param {Object} data Vue VNode.data
 */
export const getExpression = (data) => {
    const model = data.directives.filter(v => v.name === 'model');
    // eslint-disable-next-line
    const expression = data.model
        ? data.model.expression
        : (model.length ? model[0].expression : '');

    return expression;
};

/**
 * 使用指令设置数据，支持层级指令
 *
 * @param {Object} source 上下文数据
 * @param {string} selector 指令选择器
 * @param {string} value 结果值
 */
export const setExpressionData = (source, selector, value) => {
    // 如果不是多层结构
    if (selector.indexOf('.') === -1) {
        source[selector] = value;
    } else {
        const split = selector.split('.');
        const last = split.slice(-1)[0];

        split.forEach((key, index) => {
            if (index < split.length - 1) {
                source = source[key];
            }
        });

        source[last] = value;
    }
};

/**
 * 替换字符中的非数字为空
 *
 * @param {string} content 目标字符
 * @return {string}
 */
export const replaceNumber = content => content.replace(/[^\d]/g, '');

/**
 * 全角数字替换成数字
 *
 * @param {string} number 全角数字
 */
export const toRealNumber = (number) => {
    const numberArr = ['０', '１', '２', '３', '４', '５', '６', '７', '８', '９'];
    const res = number.toString().replace(/./g, (a) => {
        const num = numberArr.indexOf(a);
        if (num === -1) {
            return a;
        }

        return num;
    });

    return res;
};

/**
 * 获取是否支持 composition 事件
 *
 * @return {Promise}
 */
export const getCompositionEvent = () => (
    supportEvent(['compositionstart', 'compositionend']).then(([compositionstart, compositionend]) => (
        compositionstart && compositionend
    ))
);
